package com.asset.dispoal.poi;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;

/**
 * @description:
 * @author: yf
 * @date: 2023-08-09 09:57:56
 */
public class POIUtils {
    public static void copyRow(Workbook sourceWorkbook, Row sourceRow, Workbook targetWorkbook, Row targetRow, boolean copyValueFlag) {
        int sourceCellNum = sourceRow.getLastCellNum();
        for (int i = 0; i < sourceCellNum; i++) {
            Cell sourceCell = sourceRow.getCell(i);
            Cell targetCell = targetRow.createCell(i);
            if (sourceCell == null) {
                continue;
            }
            CellStyle sourceCellStyle = sourceWorkbook.createCellStyle();
            CellStyle targetCellStyle = targetWorkbook.createCellStyle();
            sourceCellStyle.cloneStyleFrom(sourceCell.getCellStyle());
            targetCellStyle.cloneStyleFrom(sourceCellStyle);
            targetCell.setCellStyle(targetCellStyle); //targetCell.setCellType(sourceCell.getCellType()); //删除这一行
            if (copyValueFlag) {
                switch (sourceCell.getCellType()) {
                    case NUMERIC:
                        if (DateUtil.isCellDateFormatted(sourceCell)) {
                            targetCell.setCellValue(sourceCell.getDateCellValue());
                        } else {
                            targetCell.setCellValue(sourceCell.getNumericCellValue());
                        }
                        break;
                    case STRING:
                        targetCell.setCellValue(sourceCell.getRichStringCellValue());
                        break;
                    case FORMULA:
                        targetCell.setCellFormula(sourceCell.getCellFormula());
                        break;
                    case BOOLEAN:
                        targetCell.setCellValue(sourceCell.getBooleanCellValue());
                        break;
                    case ERROR:
                        targetCell.setCellErrorValue(sourceCell.getErrorCellValue());
                        break;
                    default:
                        break;
                }
            }
        }
    }
}
